/**
Please also include CSS theme files for ag-grid.

Example:
{% block head %}
    <link href="{% static 'style/ag-grid-community/ag-grid.css' %}" rel="stylesheet">
    <link href="{% static 'style/ag-grid-community/ag-theme-quartz.css' %}" rel="stylesheet">
{% endblock %}
*/

import { ClientSideRowModelModule } from "@ag-grid-community/client-side-row-model";

import type {
    GridApi,
    GridOptions,
} from "@ag-grid-community/core";

export type {
    GridOptions,
};

import {
    createGrid,
    ModuleRegistry
} from "@ag-grid-community/core";

import { AG_GRID_LOCALE_CN } from "@ag-grid-community/locale";

import {
    GridContextMenu,
    defaultMenuEntries
} from "./components/context-menu";

import {
    defaultColumnTypes
} from './col-def';

export * from './editing';
export * from './components/edit';
export * from './components/context-menu';
export * from './col-def';


ModuleRegistry.registerModules([ClientSideRowModelModule]);

const defaultGridOptions: GridOptions = {
    rowData: null, // null: show loading
    localeText: AG_GRID_LOCALE_CN,
    defaultColDef: {
        filter: true,
        wrapHeaderText: true,
    },
    pagination: true,
    tooltipShowDelay: 500,
    // don't use enableBrowserTooltips, since it will override our custom tooltip
    // components

    onCellClicked: (event) => {
        if (!event.colDef.editable)  {
            if (event.data.hasOwnProperty('link') && event.data.link) {
                const url = event.data.link;
                if (event.event && (event.event.ctrlKey || event.event.metaKey)) {
                    window.open(url, '_blank');
                } else {
                    window.location.href = url;
                }
            }
        }
    },


    preventDefaultOnContextMenu: true,
    onCellContextMenu: (event) => {
        const existingMenus = document.querySelectorAll('[data-ag-grid-context-menu]');
        existingMenus.forEach(menu => menu.remove());
        
        const gridContextMenu = new GridContextMenu(event.api, defaultMenuEntries);
        gridContextMenu.onCellContextMenu(event);
    },

    columnTypes: defaultColumnTypes,
    
    
    // debug only
    // onCellFocused: (event) => {
    //     const row = event.api.getDisplayedRowAtIndex(event.rowIndex);
    //     const cellValue = event.api.getCellValue({
    //         rowNode: row, 
    //         colKey: event.column.colId
    //     });
    //     console.log('Focused cell value:', cellValue);
    // },
};


/**
 * Create Table
 *
 * @param options: Options will override `defaultGridOptions` defined in this library file
 * 
 */
export function createTable(container: HTMLElement, options: Partial<GridOptions> = {}): GridApi {
    const gridOptions = {
        ...defaultGridOptions,
        ...options
    };

    return createGrid(
        container,
        gridOptions,
    );
}

/**
 * @param url: should be an API url that returns corresponding data in json
 */
export function fetchDataAndSetTable(grid: GridApi, url: string) {
    // Fetch Remote Data
    fetch(url)
        .then((response) => response.json())
        .then((data: any) => grid.setGridOption("rowData", data));
    
    // TODO error handling
}

/**
 * parameters see `createTable` and `fetchDataAndSetTable`
 */
export function createAndInitilalizeTable(
    url: string,
    container: HTMLElement,
    options: Partial<GridOptions> = {}
): GridApi {
    const gridAPI = createTable(container, options);
    fetchDataAndSetTable(gridAPI, url);
    return gridAPI;
}
